package com.cy.email;

import com.cy.server.pojo.Employee;
import com.cy.server.pojo.MailConstants;
import com.rabbitmq.client.Channel;
import org.apache.poi.hssf.record.HeaderRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @peoject: yeb
 * @description: 消息接收者
 * @author: LiShaoZhuo
 * @create: 2021-05-07 17:01
 **/
@Component
public class EmailReceiver {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailReceiver.class);

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    RedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel){
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        //消息序号
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //消息id
        String msgId = (String) headers.get("spring_returned_message_correlation");
        //hashKey
        HashOperations hashOperations = redisTemplate.opsForHash();

        try {
            if (hashOperations.entries("email_log").containsKey(msgId)){
                LOGGER.error("消息已被消费===============>{}",msgId);

                /**
                * @Description: 手动确认消息
                * @Param: [message, channel]
                 * tag: 消息序号
                 * multiple: 是否多条消息
                * @return: void
                * @Author: LiShaoZhuo
                * @Date: 2021/5/8
                */
                channel.basicAck(tag, false);
                return;
            }
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(msg);
            //发件人
            messageHelper.setFrom(mailProperties.getUsername());
            //收件人
            messageHelper.setTo(employee.getEmail());
            //主题
            messageHelper.setSubject("入职欢迎邮件");
            //发送日期
            messageHelper.setSentDate(new Date());
            //邮件内容
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("jobLevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            String email = templateEngine.process("email", context);
            messageHelper.setText(email,true);
            //发送邮件
            javaMailSender.send(msg);
            LOGGER.info("邮件发送成功");
            //将消息id存入redis中
            hashOperations.put("email_log", msgId, "ok");
            //手动确认消息
            channel.basicAck(tag, false);
        } catch (Exception e) {
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ioException) {
                LOGGER.error("邮件发送失败============>{}",e.getMessage());
            }
            LOGGER.error("邮件发送失败============>{}",e.getMessage());
        }
    }
}
